package com.dys.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @Author: 疾风
 * @ClassName: OnLineNumberListener
 * @Description: 统计在线人数：
 * 1.当任何一个账户处于登录状态时,在线统计总数+1,离线时-1
 * 2.通过session监听器实现计数,但是在线人数要保存在Application域中
 * @CreateDate: 2024/09/25
 * @Version: v1.0.0
 */
@WebListener
public class OnLineNumberListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        // 向application域中 增加一个数字
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();
        Object count = application.getAttribute("count");
        if (count == null) {
            // 第一次放入数据
            application.setAttribute("count", 1);
        } else {
            int countRecord = (int) count;
            application.setAttribute("count", ++countRecord);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // 向Application域中 减少一个数字
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();
        int count = (int) application.getAttribute("count");
        application.setAttribute("count", --count);
    }
}
